package com.fengye.security.email;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Slf4j
public class EmailCodeAuthenticationProvider implements AuthenticationProvider {

    UserService userService;

    public EmailCodeAuthenticationProvider(UserService userService) {
        this.userService = userService;
    }

    /**
     * 认证
     *
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        EmailCodeAuthenticationToken token = (EmailCodeAuthenticationToken) authentication;
        UserDetails user = userService.getByEmail((String) token.getPrincipal());
        log.info("查询数据库后：{}", user);
        if (user == null) {
            throw new UsernameNotFoundException("无法获取用户信息");
        }
        System.out.println(user.getAuthorities());
        UsernamePasswordAuthenticationToken result =
                new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
                /*
                Details 中包含了 ip地址、 sessionId 等等属性
                */
        result.setDetails(token.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {

        return EmailCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }
}

